﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.WindowsAzure.StorageClient;

namespace GDoc.Data.Azure
{
    public class FilesRepository : IFilesRepository
    {
        public string Save(string name, Stream content)
        {
            if (string.IsNullOrWhiteSpace(name))
                return null;

            StorageContext context = new StorageContext();

            var cloudBlob = context.Files.GetBlobReference(name);
            
            cloudBlob.UploadFromStream(content);
            
            return name;
        }

        public Stream Get(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                return null;

            StorageContext context = new StorageContext();

            var cloudBlob = context.Files.GetBlobReference(name);

            Stream stream = new MemoryStream();

            cloudBlob.DownloadToStream(stream);

            stream.Position = 0; // Set the pointer to zero

            return stream;
        }

        public void Remove(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                return;

            StorageContext context = new StorageContext();

            var cloudBlob = context.Files.GetBlobReference(name);

            cloudBlob.DeleteIfExists();
        }
    }
}
